const fs = require('fs');
const path = require('path');
const moment = require('moment');
// 日志文件路径
const logFilePath = path.join(__dirname, 'access.log');
const key = 'qingmang' 
const {verify,sign} = require('jsonwebtoken')
const Whitelist= ['/pc/user/getLogin','/pc/student/export','/pc/parent/export','/mini/parent/parentLogin']
// token 鉴权中间件
const authMiddleware = async (ctx, next) => {  
	const token = ctx.request.header.token; // 假设 token 在 Authorization 头部中，格式为 'Bearer token'  
	console.log(ctx.url)
	// 跳过登录和注册路由的 token 校验  
	if (Whitelist.includes(ctx.url)||ctx.url.includes('/images')) {  
	  await next();  
	  return;  
	}  
	
	// 检查是否有 token  
	if (!token) {  
	  ctx.status = 200;  
	  ctx.body = {  
		code: 401,  
		msg: '身份信息已过期,请退出后重新登录'  
	  };  
	  return;  
	}  
	
	try {  
	  // 验证 token  
	  const decoded = verify(token, key); 
	  ctx.state.power = decoded.power
	  ctx.state.user = decoded.userName;
	  ctx.state.classes = decoded.classes;    
	  await next(); 
	} catch (err) {  
		console.log(err)
	  ctx.status = 200;  
	  ctx.body = {  
		code: 401,  
		msg: err  
	  };  
	  return;
	}  
  };  
function generateToken(username,power = undefined,classes = undefined){
	return sign({userName:username,power,classes},key,{algorithm:'HS256',expiresIn:"10h"})
}
// 中间件函数
const accessLogger = async (ctx, next) => {
    await next();
    
    // 记录访问者、访问时间、请求参数、返回结果
    const logInfo = {
        timestamp: moment().format(),
        user: ctx.state.user,
        method: ctx.request.method,
		url: ctx.request.url,
		body:ctx.request.body,
        query: ctx.request.query,
        response: ctx.body
    };
    
    // 将日志信息写入日志文件
    fs.appendFileSync(logFilePath, JSON.stringify(logInfo) + '\n');
    
    // 检查日志文件，删除30天以上的内容
    const currentDate = moment();
    const logData = fs.readFileSync(logFilePath, 'utf8').split('\n').filter(line => line !== '');
    const updatedLogData = logData.filter(line => {
        const logTimestamp = moment(line["timestamp"]);
        return currentDate.diff(logTimestamp, 'days') <= 15;
    });
    fs.writeFileSync(logFilePath, updatedLogData.join('\n'));
};
module.exports = {
	generateToken,
	authMiddleware,
	accessLogger
}